import { intl } from '@/utils';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';
import ProjectTreeComponent from './components/ProjectTreeComponent';
import './index.less';

import { Radio, Space } from 'antd';
import { CheckBox, LoadPanel, SelectBox } from 'devextreme-react';
import { LayoutB } from '~/public/cpas-ui';
import DetailsTableComponent from './components/DetailsTableComponent';
import { getAccountInfo, getAccountInfoMonthList } from './service';

// 创建一个 Context 对象
const TreeSelectKeyContext = React.createContext({});
const CostAnalysis = (props: any) => {
  // const { isShowGloablLoad }: any = useModel('useAdjustModel');
  const { initialState } = useModel('@@initialState');
  const { dbname, sjnd, zcbfName } = initialState?.curPart as API.CurPart;
  const { username } = initialState?.curUser as API.CurUser;
  const DataTreeRef = useRef<any>();
  const accountYearRef = useRef<any>(sjnd);

  const [leftParamsObj, setLeftParamsObj] = useState<any>({
    accountYearData: [],
    selDefaultValue: '',
    selMonthDataStart: '',
    accountMonthDataStart: [],
    selMonthDataEnd: '',
    accountMonthDataEnd: [],
    generateMonth: [],
    selDataValue: 'JFFSE',
    selectTreeNode: {},
    valueRadio: 0,
    hiddenEmptyData: true,
  });
  const dateListSelectArr = [
    { valueID: 'JFFSE', text: '借方发生额' },
    { valueID: 'DFFSE', text: '贷方发生额' },
    { valueID: 'FSE', text: '发生额' },
  ];

  const [isShowGloablLoadInit, setIsShowGloablLoadInit] = useState<boolean>(false);
  const [accountYear, setAccountYear] = useState<string>('');

  const Divstyle: React.CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '8px',
  };
  const Titlestyle: React.CSSProperties = {
    marginRight: '8px',
    width: '100px',
    textAlign: 'justify',
    textAlignLast: 'justify',
  };
  const [resizeWidth, setResizeWidth] = useState<any>(0);

  const resizeUpdate = () => {
    // 通过事件对象获取浏览器窗口的高度
    // const h = e.target.innerHeight;
    // const w = e.target.innerWidth;
    // console.log(e, '@@@ e.target');
    // setResizeHeight(h);
    const h = window.innerHeight;
    const w = window.innerWidth;
    console.log(w, h, '@@@ window.inner');
    setResizeWidth(w);
  };

  const changesetTreeSelecNode = (tempKey: string, tempData: any) => {
    setLeftParamsObj((oldData: any) => {
      let newData: any = { ...oldData };
      newData[tempKey] = tempData;
      return newData;
    });
  };

  function generateMonths(start: string, end: string): number[] {
    const startMonth = parseInt(start.slice(-2), 10); // 获取起始月份
    const endMonth = parseInt(end.slice(-2), 10); // 获取结束月份
    const months: number[] = [];
    if (startMonth === endMonth) {
      return [startMonth];
    }
    for (let month = startMonth; month <= endMonth; month++) {
      months.push(month);
    }

    return months;
  }
  const getAccountInfoMonthLis_Fun = async (tempDataID: any) => {
    const res = await getAccountInfoMonthList({ dbname, Data_ID: tempDataID });
    if (res.success) {
      console.log(res, '@@@ res');
      if (res?.data.length > 0) {
        const tempLen = res.data.length - 1;
        const tempGenerateMonthArr = generateMonths(res.data[0]?.YF, res.data[tempLen]?.YF);
        setLeftParamsObj((oldData: any) => {
          let newData: any = {
            ...oldData,
            selMonthDataStart: res.data[0]?.YF ?? '',
            accountMonthDataStart: res.data,
            selMonthDataEnd: res.data[tempLen]?.YF ?? '',
            accountMonthDataEnd: res.data,
            generateMonth: tempGenerateMonthArr,
          };
          return newData;
        });
      }
    }
  };

  // 得到 202209 至 2022012 条件  生成出 [9,10,11,12]格式的数组

  const getFetchData = async () => {
    setIsShowGloablLoadInit(true);
    const auditAdjustId: any = window.localStorage.getItem(`selectDefaultCost_${dbname}`);
    const tempYear = JSON.parse(auditAdjustId)?.tabledataId ?? sjnd;
    let findTemp = -2;
    const res: any = await getAccountInfo({ dbname });
    if (res.success) {
      findTemp = res.data.findIndex((item: any) => {
        return tempYear === item.Data_ID;
      });
      const tempIndex = findTemp >= 0 ? findTemp : 0;
      const DataId = res.data[tempIndex]?.Data_ID;
      // const displayNames = res.data[tempIndex]?.Data_ID;

      res.data.forEach((item: any, index: any) => {
        item.index = index;
        return item;
      });
      changesetTreeSelecNode('accountYearData', res.data);
      changesetTreeSelecNode('selDefaultValue', DataId);
      accountYearRef.current = DataId;
      setAccountYear(DataId);
      await getAccountInfoMonthLis_Fun(DataId);
      setIsShowGloablLoadInit(false);
    }
  };
  // 后期获取list的数据 获取到给tabs进行处理
  const onSelectionChangeds = (e: any) => {
    const v: any = window.localStorage.getItem(`selectDefaultCost_${dbname}`);
    let selectDefaultIDs = JSON.parse(v);
    selectDefaultIDs = { ...selectDefaultIDs, tabledataId: e.selectedItem.Data_ID };
    // 本地存储 持久化数据
    window.localStorage.setItem(`selectDefaultCost_${dbname}`, JSON.stringify(selectDefaultIDs));
    // AccountRef.current.show('0');
    // setSubjectLevel("全部");
    // getFetchData();
    setAccountYear(e.selectedItem.Data_ID);
    changesetTreeSelecNode('selDefaultValue', e.selectedItem.Data_ID);
    getAccountInfoMonthLis_Fun(e.selectedItem.Data_ID);
  };
  const onSelectionChangedsYFStart = (e: any) => {
    let tempGenerateMonthArr = [];

    if (e.selectedItem.YF >= leftParamsObj.selMonthDataEnd) {
      tempGenerateMonthArr = generateMonths(e.selectedItem.YF, e.selectedItem.YF);

      changesetTreeSelecNode('selMonthDataEnd', e.selectedItem.YF);
    } else {
      tempGenerateMonthArr = generateMonths(e.selectedItem.YF, leftParamsObj.selMonthDataEnd);
    }

    changesetTreeSelecNode('selMonthDataStart', e.selectedItem.YF);
    changesetTreeSelecNode('generateMonth', tempGenerateMonthArr);
  };

  const onSelectionChangedsYFEnd = (e: any) => {
    let tempGenerateMonthArr = [];
    if (e.selectedItem.YF <= leftParamsObj.selMonthDataStart) {
      tempGenerateMonthArr = generateMonths(e.selectedItem.YF, e.selectedItem.YF);
      changesetTreeSelecNode('selMonthDataStart', e.selectedItem.YF);
    } else {
      tempGenerateMonthArr = generateMonths(leftParamsObj.selMonthDataStart, e.selectedItem.YF);
    }
    changesetTreeSelecNode('selMonthDataEnd', e.selectedItem.YF);
    changesetTreeSelecNode('generateMonth', tempGenerateMonthArr);
  };
  const onSelectionChangedsData = (e: any) => {
    changesetTreeSelecNode('selDataValue', e.selectedItem.valueID);
  };

  const onChangeRadio = (e: any) => {
    changesetTreeSelecNode('valueRadio', e.target.value);
  };

  const onChangeEmptyData = (e: any) => {
    changesetTreeSelecNode('hiddenEmptyData', e.value);
  };

  useEffect(() => {
    // 页面变化时获取浏览器窗口的大小
    window.addEventListener('resize', resizeUpdate);
    resizeUpdate();
    if (dbname) {
      getFetchData();
    }
    return () => {
      // 组件销毁时移除监听事件
      window.removeEventListener('resize', resizeUpdate);
    };
  }, []);

  const topContainer = () => {
    const {
      accountYearData,
      selDefaultValue,
      selMonthDataStart,
      accountMonthDataStart,
      selMonthDataEnd,
      accountMonthDataEnd,
      selDataValue,
      valueRadio,
      hiddenEmptyData,
    } = leftParamsObj;
    return (
      <div style={{ padding: '8px', display: 'flex', justifyContent: 'space-between' }}>
        <div style={{ flex: 1, overflow: 'hidden' }}>
          <Space wrap>
            <div style={Divstyle}>
              <div style={{ marginRight: 8 }}>{intl('report.subject.account', '账套：')}</div>
              <SelectBox
                width={resizeWidth <= 1467 ? 120 : 240}
                dataSource={accountYearData}
                displayExpr="displayName"
                valueExpr="Data_ID"
                value={selDefaultValue}
                onSelectionChanged={onSelectionChangeds}
                dropDownOptions={{
                  width: '350px',
                }}
              />
            </div>

            <div style={Divstyle}>
              <div style={{ marginRight: 8 }}>{intl('report.subject.account', '月份：')}</div>
              <div style={{ ...Divstyle, flex: 1, marginBottom: 0 }}>
                <SelectBox
                  width={100}
                  dataSource={accountMonthDataStart}
                  displayExpr="YF"
                  valueExpr="YF"
                  value={selMonthDataStart}
                  onSelectionChanged={onSelectionChangedsYFStart}
                />
                <div style={{ margin: '0 8px 0' }}>至</div>
                <SelectBox
                  width={100}
                  dataSource={accountMonthDataEnd}
                  displayExpr="YF"
                  valueExpr="YF"
                  value={selMonthDataEnd}
                  onSelectionChanged={onSelectionChangedsYFEnd}
                />
              </div>
            </div>
            <div style={Divstyle}>
              <div style={{ marginRight: 8 }}>{intl('report.subject.account', '数据选项：')}</div>
              <SelectBox
                width={120}
                dataSource={dateListSelectArr}
                displayExpr="text"
                valueExpr="valueID"
                value={selDataValue}
                onSelectionChanged={onSelectionChangedsData}
              />
            </div>
            <div style={Divstyle}>
              <Radio.Group onChange={onChangeRadio} value={valueRadio}>
                <Radio value={0}>明细项目为选定科目的直接下级</Radio>
                <Radio value={1}>明细项目为选定科目的最末级</Radio>
              </Radio.Group>
            </div>
          </Space>
        </div>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            marginBottom: 8,
            width: 140,
            marginLeft: 8,
            height: 32,
          }}
        >
          <CheckBox
            text="默认无数据不显示"
            value={hiddenEmptyData}
            onValueChanged={onChangeEmptyData}
          />
        </div>
      </div>
    );
  };

  function leftContainer() {
    return (
      <div style={{ padding: '0px', height: '100%' }}>
        <div style={{ height: 'calc(100% - 0px)' }}>
          {useMemo(() => {
            return (
              <ProjectTreeComponent
                AccountDataID={accountYear ? accountYear : accountYearRef.current}
                ref={DataTreeRef}
              />



            );
          }, [accountYear])}
        </div>
      </div>
    );
  }

  // 表格结构
  function rightContainer() {
    return (
      <div style={{ margin: '0px', height: '100%' }}>
        <DetailsTableComponent />
      </div>
    );
  }

  return (
    <div style={{ width: '100%', height: '100%', overflow: 'hidden' }}>
      <TreeSelectKeyContext.Provider value={{ leftParamsObj, setLeftParamsObj }}>
        <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
          <>{topContainer()}</>
          <div style={{ flex: 1, overflow: 'hidden' }}>
            <LayoutB
              rowSize={['10%', '300px', '80%']}
              leftSlot={leftContainer()}
              rightSlot={rightContainer()}
            />
          </div>
        </div>
      </TreeSelectKeyContext.Provider>
      <LoadPanel visible={isShowGloablLoadInit} showIndicator={true} showPane={true} />
    </div>
  );
};
export default CostAnalysis;
export { TreeSelectKeyContext }; // 必须这样写 重要！
